#!/usr/bin/python
# Author: Vijay Pandurangan
# Copyright 2008
import logging
import sys
import time
import os
import gflags
import select
import termios
import tty

gflags.DEFINE_integer('stderr_level', 30, 
                      'stderr_level')
FLAGS = gflags.FLAGS

def HumanReadableTime(unix_time):

  TIMES = [('y', 365 * 24 * 60 * 60,),
           ('d', 24 * 60 * 60 ,),
           ('h', 60 * 60,),
           ('m', 60,),
           ('s', 1,),
]

  rval = []
  uv = []
  for t,d in TIMES:
    uv.append((unix_time / d, t))
    unix_time %= d
  return ''.join(['%02d%s' % (v,u) for (v,u) in uv if v])

def VijayInit(level=None, filedir='/tmp', argv=sys.argv, screen_level=None):
  if level is None:
    level = logging.INFO
  if screen_level is None:
    screen_level = logging.ERROR
  try:
    argv = gflags.FLAGS(argv)  # parse flags
  except gflags.FlagsError, e:
    print '%s\\nUsage: %s ARGS\\n%s' % (e, sys.argv[0], FLAGS)
    sys.exit(1)

  ch = logging.StreamHandler()
  ch.setLevel(screen_level)
  formatter = logging.Formatter(
    "%(levelname).1s%(asctime)s %(filename)s:%(lineno)d] %(message)s",
    datefmt='%Y%m%d:%H%M%S')
  ch.setFormatter(formatter)

  for LOG in [logging.getLogger(''), logging.getLogger()]:
    LOG.setLevel(logging.INFO)
    LOG.addHandler(ch)
  
  # Log to file
  if filedir:
    datestr = time.strftime('%Y%m%d-%H%M%S')
    basefilename = os.path.split(sys.argv[0])[-1]
    loggers = {'INFO': logging.INFO,
               'WARNING': logging.WARNING,
               'ERROR' : logging.ERROR}

    for (k, level) in loggers.items():
      fn = os.path.join(filedir, '%s.%s.%s' % (basefilename, datestr, k))
      channel = logging.FileHandler(fn)
      channel.setLevel(level)
      channel.setFormatter(formatter)
      LOG.addHandler(channel)
      symname = os.path.join(filedir, '%s.%s' % (basefilename, k))
      try:
        os.unlink(symname)
      except OSError, e:
        pass
      os.symlink(fn, symname)
    
    logging.info('starting up')


def getkey():
    old_settings = termios.tcgetattr(sys.stdin)
    tty.setraw(sys.stdin.fileno())
    select.select([sys.stdin], [], [], 0)
    answer = sys.stdin.read(1)
    termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings)
    return answer


if __name__ == '__main__':
  VijayInit()
  
    
  
